# 资产调拨模块模型
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
from .models import Asset, Department, Location


class AssetTransfer(models.Model):
    """资产调拨申请模型"""
    TRANSFER_STATUS_CHOICES = [
        ('draft', '草稿'),
        ('pending', '待审批'),
        ('approved', '已审批'),
        ('rejected', '已拒绝'),
        ('in_transit', '调拨中'),
        ('completed', '已完成'),
        ('cancelled', '已取消'),
    ]
    
    TRANSFER_TYPE_CHOICES = [
        ('department', '部门调拨'),
        ('location', '位置调拨'),
        ('user', '使用人调拨'),
        ('comprehensive', '综合调拨'),
    ]
    
    PRIORITY_CHOICES = [
        ('low', '低'),
        ('medium', '中'),
        ('high', '高'),
        ('urgent', '紧急'),
    ]
    
    # 基本信息
    transfer_number = models.CharField(max_length=100, unique=True, verbose_name="调拨单号")
    title = models.CharField(max_length=200, verbose_name="调拨标题")
    transfer_type = models.CharField(max_length=20, choices=TRANSFER_TYPE_CHOICES, verbose_name="调拨类型")
    status = models.CharField(max_length=20, choices=TRANSFER_STATUS_CHOICES, default='draft', verbose_name="调拨状态")
    priority = models.CharField(max_length=10, choices=PRIORITY_CHOICES, default='medium', verbose_name="优先级")
    
    # 申请信息
    applicant = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="申请人", related_name='transfer_applications')
    applicant_department = models.ForeignKey(Department, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="申请部门", related_name='transfer_applications')
    
    # 调拨原因
    reason = models.TextField(verbose_name="调拨原因")
    description = models.TextField(blank=True, verbose_name="详细说明")
    
    # 目标信息
    target_department = models.ForeignKey(Department, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="目标部门", related_name='transfer_targets')
    target_location = models.ForeignKey(Location, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="目标位置", related_name='transfer_targets')
    target_user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="目标使用人", related_name='transfer_targets')
    
    # 审批信息
    approver = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="审批人", related_name='transfer_approvals')
    approved_at = models.DateTimeField(null=True, blank=True, verbose_name="审批时间")
    approval_notes = models.TextField(blank=True, verbose_name="审批备注")
    
    # 执行信息
    executor = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="执行人", related_name='transfer_executions')
    started_at = models.DateTimeField(null=True, blank=True, verbose_name="开始执行时间")
    completed_at = models.DateTimeField(null=True, blank=True, verbose_name="完成时间")
    
    # 成本信息
    estimated_cost = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, verbose_name="预估成本")
    actual_cost = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, verbose_name="实际成本")
    
    # 时间信息
    expected_completion_date = models.DateTimeField(verbose_name="预期完成时间")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")
    
    class Meta:
        verbose_name = "资产调拨"
        verbose_name_plural = "资产调拨"
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['status', '-created_at']),
            models.Index(fields=['applicant', '-created_at']),
            models.Index(fields=['transfer_number']),
        ]
    
    def __str__(self):
        return f"{self.transfer_number} - {self.title}"
    
    @property
    def asset_count(self):
        """获取调拨资产数量"""
        return self.transfer_items.count()
    
    @property
    def total_value(self):
        """计算调拨资产总价值"""
        from django.db.models import Sum
        total = self.transfer_items.aggregate(
            total=Sum('asset__purchase_price')
        )['total']
        return total or 0
    
    @property
    def is_overdue(self):
        """判断是否超期"""
        if self.expected_completion_date and self.status not in ['completed', 'cancelled']:
            return timezone.now() > self.expected_completion_date
        return False
    
    @property
    def duration_days(self):
        """计算调拨耗时（天）"""
        if self.started_at and self.completed_at:
            duration = self.completed_at - self.started_at
            return duration.days
        return None
    
    def generate_transfer_number(self):
        """生成调拨单号"""
        from django.utils import timezone
        date_str = timezone.now().strftime('%Y%m%d')
        
        # 查找当天最大的序号
        today_transfers = AssetTransfer.objects.filter(
            transfer_number__startswith=f'TF{date_str}'
        ).order_by('-transfer_number')
        
        if today_transfers.exists():
            last_number = today_transfers.first().transfer_number
            sequence = int(last_number[-4:]) + 1
        else:
            sequence = 1
        
        return f'TF{date_str}{sequence:04d}'
    
    def save(self, *args, **kwargs):
        if not self.transfer_number:
            self.transfer_number = self.generate_transfer_number()
        super().save(*args, **kwargs)
    
    def can_approve(self, user):
        """判断用户是否可以审批"""
        # 这里可以根据业务规则定义审批权限
        return user.has_perm('assets.change_assettransfer') and user != self.applicant
    
    def can_execute(self, user):
        """判断用户是否可以执行"""
        return self.status == 'approved' and user.has_perm('assets.change_asset')
    
    def approve(self, approver, notes=''):
        """审批通过"""
        self.status = 'approved'
        self.approver = approver
        self.approved_at = timezone.now()
        self.approval_notes = notes
        self.save()
    
    def reject(self, approver, notes=''):
        """审批拒绝"""
        self.status = 'rejected'
        self.approver = approver
        self.approved_at = timezone.now()
        self.approval_notes = notes
        self.save()
    
    def start_execution(self, executor):
        """开始执行调拨"""
        self.status = 'in_transit'
        self.executor = executor
        self.started_at = timezone.now()
        self.save()
    
    def complete(self, executor, actual_cost=None):
        """完成调拨"""
        self.status = 'completed'
        self.executor = executor
        self.completed_at = timezone.now()
        if actual_cost is not None:
            self.actual_cost = actual_cost
        self.save()
        
        # 更新所有调拨项目的资产信息
        for item in self.transfer_items.all():
            item.apply_transfer()


class AssetTransferItem(models.Model):
    """调拨项目模型"""
    ITEM_STATUS_CHOICES = [
        ('pending', '待处理'),
        ('in_progress', '处理中'),
        ('completed', '已完成'),
        ('failed', '失败'),
    ]
    
    transfer = models.ForeignKey(AssetTransfer, on_delete=models.CASCADE, verbose_name="调拨申请", related_name='transfer_items')
    asset = models.ForeignKey(Asset, on_delete=models.CASCADE, verbose_name="资产")
    status = models.CharField(max_length=20, choices=ITEM_STATUS_CHOICES, default='pending', verbose_name="项目状态")
    
    # 原始信息（调拨前）
    original_department = models.ForeignKey(Department, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="原部门", related_name='transfer_item_origins_dept')
    original_location = models.ForeignKey(Location, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="原位置", related_name='transfer_item_origins_loc')
    original_user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="原使用人", related_name='transfer_item_origins_user')
    original_status = models.CharField(max_length=20, verbose_name="原状态")
    
    # 目标信息（调拨后）
    target_department = models.ForeignKey(Department, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="目标部门", related_name='transfer_item_targets_dept')
    target_location = models.ForeignKey(Location, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="目标位置", related_name='transfer_item_targets_loc')
    target_user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="目标使用人", related_name='transfer_item_targets_user')
    target_status = models.CharField(max_length=20, blank=True, verbose_name="目标状态")
    
    # 处理信息
    notes = models.TextField(blank=True, verbose_name="备注")
    error_message = models.TextField(blank=True, verbose_name="错误信息")
    processed_at = models.DateTimeField(null=True, blank=True, verbose_name="处理时间")
    processed_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="处理人", related_name='processed_transfer_items')
    
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")
    
    class Meta:
        verbose_name = "调拨项目"
        verbose_name_plural = "调拨项目"
        unique_together = ['transfer', 'asset']
        ordering = ['asset__asset_number']
    
    def __str__(self):
        return f"{self.transfer.transfer_number} - {self.asset.name}"
    
    def save(self, *args, **kwargs):
        # 首次保存时记录原始信息
        if not self.pk:
            self.original_department = self.asset.department
            self.original_location = self.asset.location
            self.original_user = self.asset.user
            self.original_status = self.asset.status
            
            # 设置目标信息（如果调拨申请中有指定）
            if self.transfer.target_department:
                self.target_department = self.transfer.target_department
            if self.transfer.target_location:
                self.target_location = self.transfer.target_location
            if self.transfer.target_user:
                self.target_user = self.transfer.target_user
            if not self.target_status:
                self.target_status = self.original_status
        
        super().save(*args, **kwargs)
    
    def apply_transfer(self):
        """应用调拨变更到资产"""
        try:
            # 更新资产信息
            if self.target_department:
                self.asset.department = self.target_department
            if self.target_location:
                self.asset.location = self.target_location
            if self.target_user:
                self.asset.user = self.target_user
            if self.target_status:
                self.asset.status = self.target_status
            
            self.asset.save()
            
            # 记录资产日志
            from .models import AssetLog
            AssetLog.log_action(
                asset=self.asset,
                action='transfer',
                operator=self.processed_by or self.transfer.executor,
                description=f'资产调拨完成: {self.transfer.transfer_number}',
                old_value={
                    'department': self.original_department.name if self.original_department else None,
                    'location': self.original_location.name if self.original_location else None,
                    'user': self.original_user.username if self.original_user else None,
                    'status': self.original_status,
                },
                new_value={
                    'department': self.target_department.name if self.target_department else None,
                    'location': self.target_location.name if self.target_location else None,
                    'user': self.target_user.username if self.target_user else None,
                    'status': self.target_status,
                },
                related_object=self.transfer
            )
            
            # 更新项目状态
            self.status = 'completed'
            self.processed_at = timezone.now()
            self.save()
            
        except Exception as e:
            self.status = 'failed'
            self.error_message = str(e)
            self.save()
            raise
    
    def get_changes(self):
        """获取变更内容"""
        changes = []
        
        if self.original_department != self.target_department:
            changes.append({
                'field': '部门',
                'old': self.original_department.name if self.original_department else '无',
                'new': self.target_department.name if self.target_department else '无'
            })
        
        if self.original_location != self.target_location:
            changes.append({
                'field': '位置',
                'old': self.original_location.name if self.original_location else '无',
                'new': self.target_location.name if self.target_location else '无'
            })
        
        if self.original_user != self.target_user:
            changes.append({
                'field': '使用人',
                'old': self.original_user.username if self.original_user else '无',
                'new': self.target_user.username if self.target_user else '无'
            })
        
        if self.original_status != self.target_status:
            changes.append({
                'field': '状态',
                'old': self.original_status,
                'new': self.target_status
            })
        
        return changes


class TransferApprovalFlow(models.Model):
    """调拨审批流程模型"""
    APPROVAL_STATUS_CHOICES = [
        ('pending', '待审批'),
        ('approved', '已通过'),
        ('rejected', '已拒绝'),
        ('skipped', '已跳过'),
    ]
    
    transfer = models.ForeignKey(AssetTransfer, on_delete=models.CASCADE, verbose_name="调拨申请", related_name='approval_flows')
    step_order = models.IntegerField(verbose_name="审批步骤")
    approver = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="审批人")
    status = models.CharField(max_length=20, choices=APPROVAL_STATUS_CHOICES, default='pending', verbose_name="审批状态")
    
    # 审批信息
    approved_at = models.DateTimeField(null=True, blank=True, verbose_name="审批时间")
    notes = models.TextField(blank=True, verbose_name="审批意见")
    
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")
    
    class Meta:
        verbose_name = "调拨审批流程"
        verbose_name_plural = "调拨审批流程"
        unique_together = ['transfer', 'step_order', 'approver']
        ordering = ['step_order']
    
    def __str__(self):
        return f"{self.transfer.transfer_number} - 步骤{self.step_order} - {self.approver.username}"